import { parseAddress } from '@src/api/CommonApi';
// 国际化灰度
import useFormMultiLanguage from '@hooks/useFormMultiLanguage'
import { getRootWindow } from '@src/util/dom';

export default {
  name: 'address-mixin',
  data() {
    return {
      visible: false,
      copy: '',
      pending: false,
    };
  },
  computed: {
    /** 是否开启地址街道灰度 */
    isOpenAddressStreet() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.CUSTOMER_ADDRESS_STREET_CONTROL ?? false;
    },
  },

  methods: {
    toggleModal() {
      this.visible = !this.visible;
      if (this.visible) {
        this.copy = '';
      }
    },

    /**
     * 解析地址
     * @param {*} isI18n 是否国际化
     */
    analyze() {
      this.pending = true;
      const params = {
        detailAddress: this.copy
      }

      const { internationalGray } = useFormMultiLanguage();
      if(internationalGray){
        // 国际化调用google
        params.type = 'GOOGLE'
      }
      // 是否需要获取街道（客户模块&&未开启国际化）
      const mode = this.field?.tableName || '';
      const isNeedGetStreet = mode == 'customer' && !internationalGray && this.isOpenAddressStreet;

      parseAddress(params)
        .then(res => {
          this.pending = false;
          if (!res || res.status) return this.$platform.notification({
            title: this.$t('common.form.preview.address.parseErrorTips'),
            message: res.message || '',
            type: 'error',
          });

          let {country, province, city, district, adStreet, address, lat, lng} = res.data;

          this.updateValue({
            country:country || '中国',
            province: province || '',
            city: city || '',
            dist: district || '',
            ...(isNeedGetStreet && adStreet && { street: adStreet }),
            address: address || '',
            latitude: lat || '',
            longitude: lng || '',
            addressType: (lat || lng) ? 1 : 0,
          });

          this.visible = false;
          this.copy = '';
        })
        .catch(e => console.error('e', e))
    },
  }
}